<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <div class="worktype-employee-container">
        <div class="worktype-info">
          <a-descriptions title="工种信息" :column="3" bordered size="small">
            <a-descriptions-item label="工种编码">{{ workTypeInfo.workTypeCode }}</a-descriptions-item>
            <a-descriptions-item label="工种名称">{{ workTypeInfo.workTypeName }}</a-descriptions-item>
            <a-descriptions-item label="工种描述">{{ workTypeInfo.description }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <a-divider>员工分配管理</a-divider>

        <div class="employee-operations">
          <a-button type="primary" @click="showAddEmployeeModal" icon="plus">
            添加员工
          </a-button>
          <a-button
            type="danger"
            @click="batchRemoveEmployees"
            :disabled="selectedRowKeys.length === 0"
            style="margin-left: 8px">
            批量移除
          </a-button>
          <span style="margin-left: 16px; color: #666;">
            已选择 {{ selectedRowKeys.length }} 个员工
          </span>
        </div>

        <a-table
          :columns="columns"
          :dataSource="employeeList"
          :pagination="false"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          rowKey="id"
          size="small"
          bordered
          style="margin-top: 16px;">

          <template slot="skillLevel" slot-scope="text, record">
            <j-dict-select-tag
              v-model="record.skillLevel"
              dictCode="skill_level"
              @change="(value) => handleSkillLevelChange(record, value)"
              style="width: 100%"/>
          </template>

          <template slot="certificationDate" slot-scope="text, record">
            <j-date
              v-model="record.certificationDate"
              @change="(value) => handleCertificationDateChange(record, value)"
              style="width: 100%"/>
          </template>

          <template slot="expiryDate" slot-scope="text, record">
            <j-date
              v-model="record.expiryDate"
              @change="(value) => handleExpiryDateChange(record, value)"
              style="width: 100%"/>
          </template>

          <template slot="certifier" slot-scope="text, record">
            <a-input
              v-model="record.certifier"
              @blur="(e) => handleCertifierChange(record, e.target.value)"
              placeholder="请输入认证人"/>
          </template>

          <template slot="status" slot-scope="text, record">
            <j-dict-select-tag
              v-model="record.status"
              dictCode="valid_status"
              @change="(value) => handleStatusChange(record, value)"
              style="width: 100%"/>
          </template>

          <template slot="action" slot-scope="text, record">
            <a-popconfirm title="确定移除该员工吗?" @confirm="() => removeEmployee(record)">
              <a style="color: #ff4d4f;">移除</a>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
    </a-spin>

    <!-- 添加员工模态框 -->
    <a-modal
      title="添加员工到工种"
      :width="900"
      :visible="addEmployeeVisible"
      @ok="handleAddEmployees"
      @cancel="handleAddEmployeeCancel">

      <div style="margin-bottom: 16px;">
        <a-alert message="请选择生产部门的员工添加到当前工种" type="info" show-icon />
      </div>

      <j-select-employee-modal
        ref="selectEmployeeModal"
        v-model="selectedEmployeeIds"
        :multiple="true"
        :modal-width="800"
        title="选择生产部员工"
        depart-name="生产部"
        @change="onEmployeeSelectionChange">
      </j-select-employee-modal>

      <div style="margin-top: 16px;">
        <a-alert
          v-if="selectedEmployees.length > 0"
          :message="`已选择 ${selectedEmployees.length} 名员工`"
          type="success"
          show-icon />
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { httpAction, getAction, putAction, deleteAction } from '@/api/manage'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal.vue'

export default {
  name: 'WorkTypeEmployeeModal',
  components: {
    JSelectEmployeeModal
  },
  data () {
    return {
      title: '',
      visible: false,
      confirmLoading: false,
      workTypeInfo: {},
      employeeList: [],
      selectedRowKeys: [],
      addEmployeeVisible: false,
      selectedEmployeeIds: '',
      selectedEmployees: [],
      columns: [
        {
          title: '员工姓名',
          dataIndex: 'employeeRealName',
          width: '15%'
        },
        {
          title: '员工编号',
          dataIndex: 'employeeWorkNo',
          width: '12%'
        },
        {
          title: '部门',
          dataIndex: 'departName',
          width: '15%'
        },
        {
          title: '技能等级',
          dataIndex: 'skillLevel',
          width: '12%',
          scopedSlots: { customRender: 'skillLevel' }
        },
        {
          title: '认证日期',
          dataIndex: 'certificationDate',
          width: '12%',
          scopedSlots: { customRender: 'certificationDate' }
        },
        {
          title: '到期日期',
          dataIndex: 'expiryDate',
          width: '12%',
          scopedSlots: { customRender: 'expiryDate' }
        },
        {
          title: '认证人',
          dataIndex: 'certifier',
          width: '12%',
          scopedSlots: { customRender: 'certifier' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '8%',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '8%',
          scopedSlots: { customRender: 'action' }
        }
      ],
      availableEmployeeColumns: [
        {
          title: '员工姓名',
          dataIndex: 'empName',
          width: '20%'
        },
        {
          title: '员工编号',
          dataIndex: 'empCode',
          width: '20%'
        },
        {
          title: '部门',
          dataIndex: 'department',
          width: '25%'
        },
        {
          title: '职位',
          dataIndex: 'position',
          width: '20%'
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '15%'
        }
      ],
      url: {
        getWorkTypeEmployees: '/mes/worktype/employees',
        addEmployeesToWorkType: '/mes/worktype/add-employees',
        updateEmployeeWorkType: '/mes/employee-worktype/edit',
        removeEmployeeFromWorkType: '/mes/employee-worktype/delete',
        getAvailableEmployees: '/system/employee/available'
      }
    }
  },
  methods: {
    show(workType) {
      this.workTypeInfo = { ...workType }
      this.title = `工种员工分配 - ${workType.workTypeName}`
      this.visible = true
      this.selectedRowKeys = []
      this.loadWorkTypeEmployees()
    },

    close() {
      this.visible = false
      this.employeeList = []
      this.selectedRowKeys = []
      this.workTypeInfo = {}
      this.selectedEmployeeIds = ''
      this.selectedEmployees = []
      this.addEmployeeVisible = false
    },

    handleOk() {
      this.$emit('ok')
      this.close()
    },

    handleCancel() {
      this.close()
    },

    loadWorkTypeEmployees() {
      this.confirmLoading = true
      getAction(`${this.url.getWorkTypeEmployees}/${this.workTypeInfo.id}`).then((res) => {
        if (res.success) {
          this.employeeList = res.result || []
        } else {
          this.$message.error(res.message || '加载员工列表失败')
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },

    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    showAddEmployeeModal() {
      this.addEmployeeVisible = true
      this.selectedEmployeeIds = ''
      this.selectedEmployees = []
    },

    handleAddEmployeeCancel() {
      this.addEmployeeVisible = false
      this.selectedEmployeeIds = ''
      this.selectedEmployees = []
    },

    onEmployeeSelectionChange(selectedIds, selectedEmployees) {
      this.selectedEmployeeIds = selectedIds
      this.selectedEmployees = selectedEmployees || []
    },
    
    handleAddEmployees() {
      if (this.selectedEmployees.length === 0) {
        this.$message.warning('请选择要添加的员工')
        return
      }
      
      const addData = {
        workTypeId: this.workTypeInfo.id,
        employees: this.selectedEmployees.map(emp => ({
          employeeId: emp.id,
          employeeName: emp.empName,
          skillLevel: 1,
          status: 1,
          certificationDate: null,
          expiryDate: null,
          certifier: ''
        }))
      }
      
      httpAction(this.url.addEmployeesToWorkType, addData, 'post').then((res) => {
        if (res.success) {
          this.$message.success('添加员工成功')
          this.addEmployeeVisible = false
          this.selectedEmployeeIds = ''
          this.selectedEmployees = []
          this.loadWorkTypeEmployees()
        } else {
          this.$message.error(res.message || '添加员工失败')
        }
      });
    },
    
    handleSkillLevelChange(record, value) {
      this.updateEmployeeWorkType(record, { skillLevel: value });
    },
    
    handleCertificationDateChange(record, value) {
      this.updateEmployeeWorkType(record, { certificationDate: value });
    },
    
    handleExpiryDateChange(record, value) {
      this.updateEmployeeWorkType(record, { expiryDate: value });
    },
    
    handleCertifierChange(record, value) {
      this.updateEmployeeWorkType(record, { certifier: value });
    },
    
    handleStatusChange(record, value) {
      this.updateEmployeeWorkType(record, { status: value });
    },
    
    updateEmployeeWorkType(record, updateData) {
      const data = {
        id: record.id,
        ...updateData
      };
      
      putAction(this.url.updateEmployeeWorkType, data).then((res) => {
        if (res.success) {
          // 更新本地数据
          Object.assign(record, updateData);
          this.$message.success('更新成功');
        } else {
          this.$message.error(res.message || '更新失败');
          // 重新加载数据以恢复原值
          this.loadWorkTypeEmployees();
        }
      });
    },
    
    removeEmployee(record) {
      deleteAction(`${this.url.removeEmployeeFromWorkType}?id=${record.id}`).then((res) => {
        if (res.success) {
          this.$message.success('移除员工成功');
          this.loadWorkTypeEmployees();
        } else {
          this.$message.error(res.message || '移除员工失败');
        }
      });
    },
    
    batchRemoveEmployees() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择要移除的员工');
        return;
      }
      
      this.$confirm({
        title: '确认移除',
        content: `确定要移除选中的 ${this.selectedRowKeys.length} 个员工吗？`,
        onOk: () => {
          const ids = this.selectedRowKeys.join(',');
          deleteAction(`${this.url.removeEmployeeFromWorkType}?ids=${ids}`).then((res) => {
            if (res.success) {
              this.$message.success('批量移除成功');
              this.selectedRowKeys = [];
              this.loadWorkTypeEmployees();
            } else {
              this.$message.error(res.message || '批量移除失败');
            }
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.worktype-employee-container {
  padding: 16px 0;
}

.worktype-info {
  margin-bottom: 24px;
}

.employee-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style>
